package com.tensquare.friend.controller;

import com.tensquare.friend.enums.LikeEnum;
import com.tensquare.friend.service.FriendService;
import entity.Result;
import enums.ResultEnum;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.ResultUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@RestController
@RequestMapping("/friend")
public class FriendController {

    @Autowired
    private FriendService friendService;

    @Autowired
    private HttpServletRequest request;

    @DeleteMapping("/{friendid}")
    public Result remove(@PathVariable String friendid) {
        Claims claims = (Claims) request.getAttribute("user_claims");
        return Optional.ofNullable(claims).map(c -> {
            friendService.deleteFriend(c.getId(), friendid);
            return ResultUtil.valueOf(ResultEnum.DELETE_SUCCESS);
        }).orElse(ResultUtil.valueOf(ResultEnum.ACCESS_ERROR));
    }

    /**
     * 添加喜欢或者不喜欢
     *
     * @param friendid
     * @param type
     * @return
     */
    @PutMapping("/like/{friendid}/{type}")
    public Result addFriend(@PathVariable String friendid, @PathVariable String type) {
        Claims claims = (Claims) request.getAttribute("user_claims");
        return Optional.ofNullable(claims)
                .map(c -> {
                    if (LikeEnum.lIKE.getIslike().equals(type)) {
                        //喜欢
                        if (friendService.addFriend(c.getId(), friendid) == 0) {
                            return ResultUtil.valueOf(ResultEnum.REP_ERROR);
                        }
                    } else {
                        //不喜欢
                        friendService.addNoFriend(c.getId(), friendid);
                    }
                    return ResultUtil.successMsg("操作成功");
                })
                .orElse(ResultUtil.valueOf(ResultEnum.ACCESS_ERROR));
    }

}
